package com.dddframework.security.infras.config;

import com.dddframework.kit.lang.MapKit;
import com.dddframework.security.domain.auth.component.BaseWebResponseExceptionTranslator;
import com.dddframework.security.domain.auth.component.RedisClientDetailsService;
import com.dddframework.security.domain.auth.model.AuthUser;
import com.dddframework.security.domain.auth.service.IUserDetailService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 认证服务器配置
 *
 * @author zhouzx
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * sys_oauth_client 表的字段，id、client_secret
     */
    private final String CLIENT_FIELDS = "id, CONCAT('{noop}',client_secret) as client_secret, resource_ids, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove";
    /**
     * JdbcClientDetailsService 查询语句
     */
    private final String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + " from sys_oauth_client";
    /**
     * 默认的查询语句
     */
    private final String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by id";

    /**
     * 按条件client_id 查询
     */
    private final String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where id = ?";
    private final DataSource dataSource;
    private final IUserDetailService userDetailService;
    private final AuthenticationManager authenticationManagerBean;
    private final RedisConnectionFactory redisConnectionFactory;

    @Override
    @SneakyThrows
    public void configure(ClientDetailsServiceConfigurer clients) {
        RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource);
        clientDetailsService.setSelectClientDetailsSql(DEFAULT_SELECT_STATEMENT);
        clientDetailsService.setFindClientDetailsSql(DEFAULT_FIND_STATEMENT);
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.allowFormAuthenticationForClients().checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancer())
                .userDetailsService(userDetailService)
                .authenticationManager(authenticationManagerBean)
                .reuseRefreshTokens(false)
                .pathMapping("/oauth/confirm_access", "/token/confirm_access")
                .exceptionTranslator(new BaseWebResponseExceptionTranslator());
    }


    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix("base_oauth");
        tokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
            @Override
            public String extractKey(OAuth2Authentication authentication) {
                return super.extractKey(authentication) + ":" + AuthUser.of(authentication).getTenantId();
            }
        });
        return tokenStore;
    }

    /**
     * token增强，客户端模式不增强。
     *
     * @return TokenEnhancer
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            if ("client_credentials".equals(authentication.getOAuth2Request().getGrantType())) {
                return accessToken;
            }
            AuthUser authUser = (AuthUser) authentication.getUserAuthentication().getPrincipal();
            Map<String, Object> additionalInfo = MapKit.of(authUser);
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            log.info("token enhancer auth is {}, map is {}", authUser, additionalInfo);
            return accessToken;
        };
    }
}